<template>
  <div class="warehouse-container">
    <h1>仓库管理系统</h1>

    <!-- 商品添加表单 -->
    <form @submit.prevent="addItem" class="add-form">
      <input v-model="newItem.name" placeholder="商品名称" required>
      <input v-model="newItem.description" placeholder="描述">
      <input v-model.number="newItem.price" placeholder="价格" type="number" step="0.01">
      <input v-model.number="newItem.stock" placeholder="库存数量" type="number">
      <button type="submit">添加商品</button>
    </form>

    <!-- 商品列表展示 -->
    <ul class="item-list">
      <li v-for="(item, index) in items" :key="item.id" class="item-card">
        <h3>{{ item.name }}</h3>
        <p>描述: {{ item.description }}</p>
        <p>价格: ￥{{ item.price.toFixed(2) }}</p>
        <p>库存: {{ item.stock }}</p>
        <button @click="deleteItem(index)">删除</button>
        <button @click="prepareEditItem(item, index)">编辑</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { Warehouse } from '../models/Warehouse';

export default {
  data() {
    return {
      warehouse: new Warehouse(),
      newItem: {
        id: null,
        name: '',
        description: '',
        price: 0,
        stock: 0
      },
      items: [],
      editIndex: -1 // 用于记录正在编辑的商品索引
    };
  },
  methods: {
    // 添加新商品
    addItem() {
      if (!this.newItem.name || this.newItem.price <= 0 || this.newItem.stock < 0) {
        alert('请填写正确的商品信息');
        return;
      }

      const id = Date.now(); // 使用时间戳作为唯一 ID
      this.newItem.id = id;
      this.warehouse.addItem(this.newItem);
      this.items = this.warehouse.getAllItems();
      this.resetForm();
    },

    // 删除商品
    deleteItem(index) {
      const item = this.items[index];
      this.warehouse.removeItem(item.id);
      this.items = this.warehouse.getAllItems();
    },

    // 准备编辑商品
    prepareEditItem(item, index) {
      this.newItem = { ...item };
      this.editIndex = index;
    },

    // 重置表单
    resetForm() {
      this.newItem = {
        id: null,
        name: '',
        description: '',
        price: 0,
        stock: 0
      };
      this.editIndex = -1;
    }
  }
};
</script>

<style scoped>
.warehouse-container {
  padding: 20px;
}
.add-form {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
.add-form input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.add-form button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.item-list {
  list-style-type: none;
  padding: 0;
}
.item-card {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 8px;
}
.item-card button {
  margin-right: 10px;
  margin-top: 10px;
}
</style>